package com.learnyou.server.xingzuo.controller.app.impl;

import com.learnyou.server.xingzuo.biz.common.WechatClientBiz;
import com.learnyou.server.xingzuo.controller.app.WechatThirdApiResource;
import com.learnyou.server.xingzuo.dto.paramDTO.wechat.WechatEncryptParamDTO;
import com.learnyou.server.xingzuo.dto.paramDTO.wechat.third.WechatThirdAuthCodeDTO;
import com.learnyou.server.xingzuo.dto.paramDTO.wechat.third.WechatThirdAuthTicketDTO;
import com.learnyou.server.xingzuo.dto.paramDTO.wechat.third.WechatThirdPrivateAuthCodeDTO;
import com.learnyou.server.xingzuo.dto.wechat.WechatThirdAuthInfo;
import com.learnyou.server.xingzuo.dto.wechat.WechatThirdAuthorizerResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@RestController
public class WechatThirdApiController implements WechatThirdApiResource {

    @Resource
    private WechatClientBiz wechatClientBiz;


    @Override
    public String authEvent(WechatEncryptParamDTO params, String encryptData) {

        log.info("event detail: {}", encryptData);
        log.info("params: {}", params.toString());
        WechatThirdAuthTicketDTO authPushData = wechatClientBiz.parseTicketFromPush(params.getMsg_signature(), params.getTimestamp(), params.getNonce(), encryptData);

        log.info("auth push data: {}", authPushData);
        return "success";
    }

    @Override
    public void authCallback(WechatThirdAuthCodeDTO params, HttpServletResponse response) {
        log.info("callback params: {}", params);

        WechatThirdAuthInfo authInfo = wechatClientBiz.getAuthInfo(params.getAuth_code());
        WechatThirdAuthorizerResultDTO thirdAuthorizerResult = wechatClientBiz.getAuthorizerInfo(authInfo);

        log.info("WechatThirdAuthorizerResultDTO: {}", thirdAuthorizerResult);

        boolean bindSuccess = true;
        String bindResultMsg = "";

        // 尝试更新绑定机构公众号
        // 一个appid只能和一个机构绑定
        try {
//            orgBiz.updateOrgMpInfo(params.getOrgId(), thirdAuthorizerResult);
        } catch (Exception ex) {
            log.error("update mp info error:", ex);
            bindSuccess = false;
            bindResultMsg = "公众号授权失败，可能绑定过其他机构。";
        }

        // 构建跳转链接地址
        String redirectUrl = "/organization/organizationInfo?bindState=" + bindSuccess + "&bindMsg=" + bindResultMsg;
        try {
            response.sendRedirect(redirectUrl);
        } catch (Exception ex) {
            log.error("redirect error:", ex);
        }
    }

    @Override
    public void privateAuthCallbackOfCode(WechatThirdPrivateAuthCodeDTO privateAuthCodeDTO, HttpServletResponse response) throws IOException {

        if (Objects.nonNull(privateAuthCodeDTO)) {
            log.info("WechatThirdPrivateAuthCodeDTO: {}", privateAuthCodeDTO);
            String code = privateAuthCodeDTO.getCode();

            // 第三方公众号的openid
            String openId = wechatClientBiz.getThirdUserOpenId(code, privateAuthCodeDTO.getAppid());
            log.info("mp_openid: {}", openId);
            String query = String.format("mpOpenid=%s&mpAppid=%s", openId, privateAuthCodeDTO.getAppid());
            log.info("query: {}", query);
            String linkUrl = wechatClientBiz.generateWxaUrlLink(query);
            log.info("linkUrl: {}", linkUrl);
            response.sendRedirect(linkUrl);
        } else {
            log.error("WechatThirdPrivateAuthCodeDTO is null");
        }
    }
}
